package com.xz.filter;

import org.glassfish.jersey.message.internal.ReaderWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 * User: mbao
 * Date: 14-3-26
 * Time: 上午11:36
 * To change this template use File | Settings | File Templates.
 */
@Provider
public class RequestFilter implements ContainerRequestFilter {
    private static Logger log = LoggerFactory.getLogger(RequestFilter.class);
    private static Logger postLog = LoggerFactory.getLogger("postInfo");

    @Context
    HttpServletRequest request;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        log.debug("REQUEST HEADER:{}", requestContext.getHeaders());
        if (requestContext.getMethod().equals("POST")) {
            postLog.info("IP:{},METHOD:{},URL:{},POST CONTENT:{}", getIpAddr(), requestContext.getMethod(), requestContext.getUriInfo().getRequestUri().toString(), this.getPostContent(requestContext));
        }
        log.info("IP:{},METHOD:{},URL:{}", getIpAddr(), requestContext.getMethod(), requestContext.getUriInfo().getRequestUri().toString());

    }

    public String getPostContent(ContainerRequestContext request) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = request.getEntityStream();
        try {
            ReaderWriter.writeTo(in, out);
            byte[] requestEntity = out.toByteArray();
            request.setEntityStream(new ByteArrayInputStream(requestEntity));
            return new String(requestEntity);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return "";
    }

    public String getIpAddr() {
        String ip = request.getHeader(" x-forwarded-for ");
        if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
            ip = request.getHeader(" Proxy-Client-IP ");
        }
        if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
            ip = request.getHeader(" WL-Proxy-Client-IP ");
        }
        if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
